<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
//ini_set('display_errors', '1'); // for test

class Apireceiver extends CI_Controller {

	var $TO_USER;
	var $FROM_USER;
	var $NOW_TIME;
	public function index(){
		// $this->valid(); //for chech
		
		$post_str = isset($GLOBALS["HTTP_RAW_POST_DATA"]) ? $GLOBALS["HTTP_RAW_POST_DATA"] : '';
		if (!empty($post_str)){
			$post_data = simplexml_load_string($post_str, 'SimpleXMLElement', LIBXML_NOCDATA);
			
			$MsgType = trim($post_data->MsgType);
			$FromUserName = trim($post_data->FromUserName);
			$ToUserName = trim($post_data->ToUserName);
			$CreateTime = trim($post_data->CreateTime);
			$MsgId = trim($post_data->MsgId);
			
			// for 回复
			$this->TO_USER = $FromUserName;
			$this->FROM_USER = $ToUserName;
			$this->NOW_TIME = time();
			
			// message入库
			$msg_types = array('text' => 1, 'image' => 2, 'voice' => 3, 'video' => 4, 'location' => 5, 'link' => 6);
			$message = array(
					'from_user' => $FromUserName,
					'msg_id' => $MsgId,
					'type' => $msg_types[$MsgType],
					'msg_time' => date('Y-m-d H:i:s', $CreateTime),
					'title' => trim($post_data->Title),
					'summary' => trim($post_data->Description),
					'content' => trim($post_data->Content),
					'media_id' => trim($post_data->MediaId),
					'thumb_media_id' => trim($post_data->ThumbMediaId),
					'picurl' => trim($post_data->PicUrl),
					'format' => trim($post_data->Format),
					'location_x' => trim($post_data->Location_X),
					'location_y' => trim($post_data->Location_Y),
					'scale' => trim($post_data->Scale),
					'label' => trim($post_data->Label),
					'url' => trim($post_data->Url),
					'add_time' => date('Y-m-d H:i:s', $this->NOW_TIME)
				);
			$this->load->model('Message_model', 'Mmessage');
			$this->Mmessage->add($message);
			
			switch ($MsgType){
				case 'text':
					$content_from = trim($post_data->Content);
					break;
				case 'image':
				case 'voice':
				case 'video':
				case 'location':
				case 'link':
					$this->default_reply();
					break;
				default:
					$this->default_reply();
			}
			
			$material_list = array();
			$wordlist = $this->scws($content_from);
			if ($wordlist){
				$word_arr_where = array_fill(0, count($wordlist), '?');
				$word_str_where = implode(',', $word_arr_where);
				$this->load->model('Autoreply_model', 'Mautoreply');
				$material_list = $this->Mautoreply->get_rule_list("k.keyword in({$word_str_where})", $wordlist);
			}
			if (empty($material_list)){
				$this->default_reply();
			}
				
			// 在多个关键词中随机选一个rule的material id
			$_key = rand(0, count($material_list) - 1);
			$material_id_str = $material_list[$_key]['material_id'];
			$material_type = $material_list[$_key]['material_type'];
				
			// 回复文本
			if ($material_type == 6){
				$this->reply(6, $material_list[$_key]['content']);
			}
			
			// 回复类型不是文本，那么随机选一个 material
			$material_id_arr = explode(',', $material_id_str);
			$_key = rand(0, count($material_id_arr) - 1);
			$material_id = $material_id_arr[$_key];

			$this->load->model('Material_model', 'Mmaterial');
			$material = $this->Mmaterial->get_list('id=?', array($material_id));
			
			$material_type = $material[0]['type'];
			if ($material_type == 2){
				$_material = $this->Mmaterial->get_list('multi_id=?', array($material[0]['id']));
				if ($_material){
					$material = array_merge($material, $_material);
				}
			}
			$this->reply($material_type, '', $material);
			
			// reply返回失败，将回复默认消息
			$this->default_reply();
		}else {
			$this->err_msg('消息空！');
		}

	}
	
	public function scwsdisc(){
		is_login($this->session);
		
		$this->load->model('Autoreply_model', 'Mautoreply');
		$keyword_list = $this->Mautoreply->get_keyword();
		$keywords = array();
		$code = 0;
		$err_msg = '';
		if ($keyword_list){
			foreach ($keyword_list as $_keyword){
				$keywords[$_keyword['keyword']] = $_keyword['keyword'];
			}
		}
		if (!empty($keywords)){
			$disc = $this->config->config['SCWS_DISC_DUREX'];
			$re = @file_put_contents($disc, implode("\n", $keywords));
			if (!$re){
				$code = 1;
				$err_msg = 'write file error!';
			}
		}else {
			$code = 1;
			$err_msg = 'keyword list read from db error!';
		}
		
		exit(json_encode(array('code' => $code, 'msg' => $err_msg)));
	}
	
	private function reply($type, $contents = '', $materials = array()){
		switch ($type){
			case '1':
			case '2':
				// 单图文 多图文
				$tpl_article = '<item><Title><![CDATA[%s]]></Title><Description><![CDATA[%s]]></Description><PicUrl><![CDATA[%s]]></PicUrl><Url><![CDATA[%s]]></Url></item>';
				$articles = '';
				foreach ($materials as $material){
					$url = BASEWEBSITE . 'material/detail?id=' . $material['id'];
					$cover = BASEWEBSITE . $material['cover'];
					$articles .= sprintf($tpl_article, $material['title'], $material['summary'], $cover, $url) . "\n";
				}
				$count = count($materials);
				
				$cont_tpl = $this->msg_tmpl('news');
				echo sprintf($cont_tpl, $this->TO_USER, $this->FROM_USER, $this->NOW_TIME, $count, $articles);
				break;
			case '3':
				// 图片
				$cont_tpl = $this->msg_tmpl('image');
				echo sprintf($cont_tpl, $this->TO_USER, $this->FROM_USER, $this->NOW_TIME, $materials[0]['media_id']);
				break;
			case '4':
				// 语音
				$cont_tpl = $this->msg_tmpl('voice');
				echo sprintf($cont_tpl, $this->TO_USER, $this->FROM_USER, $this->NOW_TIME, $materials[0]['media_id']);
				break;
			case '5':
				// 视频
				$cont_tpl = $this->msg_tmpl('video');
				echo sprintf($cont_tpl, $this->TO_USER, $this->FROM_USER, $this->NOW_TIME, $materials[0]['media_id'], $materials[0]['title'], $materials[0]['summary']);
				break;
			case '6':
				// 文本
				$cont_tpl = $this->msg_tmpl('text');
				echo sprintf($cont_tpl, $this->TO_USER, $this->FROM_USER, $this->NOW_TIME, $contents);
				break;
			default:
				return false;
		}
		exit;
	}
	
	private function default_reply(){
		echo 'default reply!';
		exit;
	}
	
	private function msg_tmpl($msg_type){
		switch ($msg_type){
			case 'text':
				// 文本
				$tpl = '<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[text]]></MsgType>
					<Content><![CDATA[%s]]></Content>
					</xml>';
				break;
			case 'image':
				// 图片
				$tpl = '<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[image]]></MsgType>
					<Image>
						<MediaId><![CDATA[%s]]></MediaId>
					</Image>
					</xml>';
				break;
			case 'voice':
				// 语音
				$tpl = '<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[voice]]></MsgType>
					<Voice>
						<MediaId><![CDATA[%s]]></MediaId>
					</Voice>
					</xml>';
				break;
			case 'video':
				// 视频
				$tpl = '<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[video]]></MsgType>
					<Video>
						<MediaId><![CDATA[%s]]></MediaId>
						<Title><![CDATA[%s]]></Title>
						<Description><![CDATA[%s]]></Description>
					</Video> 
					</xml>';
				break;
			case 'music':
				// 音乐
				$tpl = '<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[music]]></MsgType>
					<Music>
						<Title><![CDATA[%s]]></Title>
						<Description><![CDATA[%s]]></Description>
						<MusicUrl><![CDATA[%s]]></MusicUrl>
						<HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
						<ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
					</Music>
					</xml>';
				break;
			case 'news':
				// 图文
				$tpl = '<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[news]]></MsgType>
					<ArticleCount>%s</ArticleCount>
					<Articles>%s</Articles>
					</xml> ';
				break;
			default:
				$tpl = false;
		}
		
		return $tpl;
	}
	
	private function scws($str = ''){
		if (empty($str)){
			return false;
		}
		$disc = $this->config->config['SCWS_DISC_DUREX'];
		$rule = $this->config->config['SCWS_RULE_UTF8'];
		
		$so = scws_new();
		$so->set_charset('utf8');
		$so->set_dict($disc, SCWS_XDICT_TXT);
		$so->set_rule($rule);
		$so->send_text($str);
		$word_arr = array();
		while ($tmp = $so->get_result()){
			foreach ($tmp as $word){
				$word_arr[] = $word['word'];
			}
		}
		$so->close();
		$word_arr = array_unique($word_arr);
		return $word_arr;
	}

	private function valid()
	{
		$signature = getdata($this->input->get('signature'));
		$timestamp = getdata($this->input->get('timestamp'));
		$nonce = getdata($this->input->get('nonce'));
		$echostr = getdata($this->input->get('echostr'));
		$token = $this->config->config['WECHAT_TOKEN'];
		
		$tmp_arr = array($token, $timestamp, $nonce);
		sort($tmp_arr);
		$tmp_str = sha1(implode($tmp_arr));

		if ($tmp_str != $signature){
			$this->err_msg('验证失败！');
		}else {
			exit($echostr);
		}
	}
	
	private function err_msg($msg = 'Error!'){
		exit($msg);
	}

}
